package com.songyang.mqttandothers.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songyang.mqttandothers.bean.LogBean;
import com.songyang.mqttandothers.mapper.LogMapper;
import com.songyang.mqttandothers.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, LogBean> implements LogService {

    @Autowired
    private LogMapper logMapper;

    @Override

    public IPage<LogBean> getAllLog(Integer userId, String keyWord, Integer nuPage, Integer pageSize) {
        IPage<LogBean> page = new Page<>(nuPage, pageSize);
        QueryWrapper<LogBean> queryWrapper = new QueryWrapper<LogBean>().eq("user_id", userId).orderByDesc("time");

        if (keyWord != null && !keyWord.equals("null")) {
            queryWrapper.like("device_id", keyWord);
        }
        return logMapper.selectPage(page, queryWrapper);

    }

    @Override
    public Integer setLog(Integer userId, Integer deviceId, String msg) {
        LogBean logBean = new LogBean();
        logBean.setDeviceId(deviceId);
        logBean.setUserId(userId);
        logBean.setMsg(msg);
        logBean.setTime(getTime());
        return logMapper.insert(logBean);
    }

    @Override
    public IPage<LogBean> find(Integer deviceId, Integer nuPage, Integer pageSize) {
        QueryWrapper<LogBean> queryWrapper = new QueryWrapper<LogBean>().like("device_id", deviceId).orderByDesc("time");
        IPage<LogBean> page = new Page<>(nuPage, pageSize);
        return logMapper.selectPage(page, queryWrapper);
    }

    public String getTime() {
        Date date = new Date();//创建时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(date);
    }
}
